import requests
import json
from function import function_help


class Login(object):

    def sso_login(self):
        headers = {'Content-Type': 'application/json'}
        verify = function_help.Function_Help().get_yaml_info()['info']['sso']['url_shyd_strategy'] + '/common/verify'
        response_verity = requests.get(verify, headers=headers)
        uuid = json.loads(response_verity.text)['data']['uuid']
        sso_login = function_help.Function_Help().get_yaml_info()['info']['sso']['url_shyd_strategy'] + '/login'
        account = function_help.Function_Help().get_yaml_info()['info']['user_info']['sys_user_encryption']
        password = function_help.Function_Help().get_yaml_info()['info']['user_info']['sys_passwd_encryption']
        data_login = {"account": account, "password": password, "code": "jnrzj", "uuid": uuid}
        response_login = requests.post(url=sso_login, data=json.dumps(data_login), headers=headers)
        token = json.loads(response_login.text)['data']['token']
        cookies = response_login.headers.get("Set-Cookie")
        cookie = cookies.split(',')[2].split(';')[0].strip()
        headers['Authorization'] = f"Bearer {token.strip()}"
        headers['Cookie'] = cookie
        return headers

    def user_login(self):
        headers = {'Content-Type': 'application/json'}
        verify = function_help.Function_Help().get_yaml_info()['info']['user']['url_shyd_strategy'] + '/common/verify'
        response_verity = requests.get(verify, headers=headers)
        uuid = json.loads(response_verity.text)['data']['uuid']
        user_login = function_help.Function_Help().get_yaml_info()['info']['user']['url_shyd_strategy'] + '/login'
        #  account的数据是sysadmin用户加密后的
        account = function_help.Function_Help().get_yaml_info()['info']['user_info']['sys_user_encryption']
        password = function_help.Function_Help().get_yaml_info()['info']['user_info']['sys_passwd_encryption']
        data_login = {"account": account, "password": password, "code": "jnrzj", "uuid": uuid}
        response_login = requests.post(url=user_login, data=json.dumps(data_login), headers=headers)
        token = json.loads(response_login.text)['data']['token']
        cookies = response_login.headers.get("Set-Cookie")
        cookie = cookies.split(',')[2].split(';')[0].strip()
        headers['Authorization'] = f"Bearer {token.strip()}"
        headers['Cookie'] = cookie
        return headers


if __name__ == '__main__':
    test = Login()
    result = test.user_login()
    print(result)
